import mx.utils.Delegate;

import org.papervision3d.core.geom.Vertex3D;
import org.papervision3d.materials.ColorMaterial;
import org.papervision3d.scenes.MovieScene3D;

/**
 * Ribbon is a sequence of RibbonSegments.
 *
 * by Felix Turner
 * www.airtightinteractive.com
 */

class Ribbon{

	static private var RIBBON_AREA_RADIUS :Number = 3000;	
	static private var RIBBON_LENGTH :Number = 30;	
	
	private var _PenTwnX:BezierTween;	
	private var _PenTwnY:BezierTween;	
	private var _pen:Vertex3D;	
	private var _lastPenLoc:Vertex3D;	
	private var _ribbonMaterial:ColorMaterial;
	private var _segmentCount:Number;	
	private var _scene:MovieScene3D;
	
	private var _colval:Number;
		
	function Ribbon(scene:MovieScene3D){
		
		_scene = scene;
				
		_pen = new Vertex3D();
		_lastPenLoc = new Vertex3D();	
		
		_PenTwnX = new BezierTween(_pen, "x", _pen.x, getRndPosn(), RIBBON_LENGTH, false, getRndPosn(), getRndPosn());
		_PenTwnY = new BezierTween(_pen, "y", _pen.y, getRndPosn(), RIBBON_LENGTH, false, getRndPosn(), getRndPosn());
		
		_PenTwnX.onMotionFinished = Delegate.create(this,doBezTween);
		_PenTwnX.onMotionChanged = Delegate.create(this,onChange);
		
		_segmentCount = 0;
		
		doBezTween();		
	}	
	
	function doBezTween(){
	
		buildRndMaterial();		
		_PenTwnX.continueTo(getRndPosn(),RIBBON_LENGTH, getRndPosn(),getRndPosn());
		_PenTwnY.continueTo(getRndPosn(),RIBBON_LENGTH, getRndPosn(),getRndPosn());
	}
		
	function onChange(){
						
		_segmentCount++;
		if (_segmentCount > RIBBON_LENGTH){
			_scene.shift();
		}
		
		var seg = new RibbonSegment( _ribbonMaterial, _lastPenLoc.x , _lastPenLoc.y, _pen.x,_pen.y);
		_lastPenLoc.x = _pen.x;
		_lastPenLoc.y = _pen.y;
			
		// Include in scene
		_scene.push(seg);					
	}	
	
	function getRndPosn():Number{		
		return Math.random() * RIBBON_AREA_RADIUS - RIBBON_AREA_RADIUS/2;
	}
		
	function buildRndMaterial(){
		_colval = Math.random() * 0xFFFFFF;		
		_ribbonMaterial =  new ColorMaterial(_colval, 70)	;
		_ribbonMaterial.oneSide = false; // Make it double sided
	}
	
	
	
}